{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Boring preliminaries\n",
    "import re\n",
    "import math\n",
    "import string\n",
    "from collections import Counter\n",
    "from __future__ import division"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<center>\n",
    "<h1>Statistical Natural Language Processing in Python.\n",
    "<br><font color=blue>or</font>\n",
    "<br>How To Do Things With Words.  And Counters.\n",
    "<br><font color=blue>or</font>\n",
    "<br>Everything I Needed to Know About NLP I learned From Sesame Street.\n",
    "<br>Except Kneser-Ney Smoothing.\n",
    "<br>The Count Didn't Cover That.\n",
    "<br>\n",
    "<br><img src='http://norvig.com/ipython/the-count.jpg'> \n",
    "<br>*One, two, three, ah, ah, ah!* &mdash; The Count\n",
    "</center>\n",
    "<hr>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(1) Data: Text and Words\n",
    "========\n",
    "\n",
    "Before we can do things with words, we need some words.  First we need some *text*, possibly from a *file*.  Then we can break the text into words.  I happen to have a big text called [big.txt](file:///Users/pnorvig/Documents/ipynb/big.txt).  We can read it, and see how big it is (in characters):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6488409"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "TEXT = file('big.txt').read()\n",
    "len(TEXT)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So, six million characters.\n",
    "\n",
    "Now let's break the text up into words (or more formal-sounding, *tokens*).  For now we'll ignore all the punctuation and numbers, and anything that is not a letter."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def tokens(text):\n",
    "    \"List all the word tokens (consecutive letters) in a text. Normalize to lowercase.\"\n",
    "    return re.findall('[a-z]+', text.lower()) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['this', 'is', 'a', 'test', 'this', 'is']"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tokens('This is: A test, 1, 2, 3, this is.')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1105211"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "WORDS = tokens(TEXT)\n",
    "len(WORDS)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So, a million words.  Here are the first 10:\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['the', 'project', 'gutenberg', 'ebook', 'of', 'the', 'adventures', 'of', 'sherlock', 'holmes']\n"
     ]
    }
   ],
   "source": [
    "print(WORDS[:10])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(2) Models: Bag of Words\n",
    "====\n",
    "\n",
    "The list `WORDS` is a list of the words in the `TEXT`, but it can also serve as a *generative model* of text. We know that language is very complicated, but we can create a simplified model of language that captures part of the complexity.  In the *bag of words* model, we ignore the order of words, but maintain their frequency.  Think of it this way: take all the words from the text, and throw them into a bag.  Shake the bag, and then generating a sentence consists of pulling words out of the bag one at a time.  Chances are it won't be grammatical or sensible, but it will have words in roughly the right proportions.  Here's a function to sample an *n* word sentence from a bag of words:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def sample(bag, n=10):\n",
    "    \"Sample a random n-word sentence from the model described by the bag of words.\"\n",
    "    return ' '.join(random.choice(bag) for _ in range(n))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'the mucous acute ordered inevitability collision collection a attained august'"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sample(WORDS)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Another representation for a bag of words is a `Counter`, which is a dictionary of `{'word': count}` pairs.  For example,"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Counter({'a': 2, 'is': 2, 'test': 2, 'this': 1, 'it': 1})"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Counter(tokens('Is this a test? It is a test!'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A `Counter` is like a `dict`, but with a few extra methods.  Let's make a `Counter` for the big list of `WORDS` and get a feel for what's there:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('the', 80029), ('of', 40025), ('and', 38312), ('to', 28766), ('in', 22047), ('a', 21155), ('that', 12512), ('he', 12401), ('was', 11410), ('it', 10681)]\n"
     ]
    }
   ],
   "source": [
    "COUNTS = Counter(WORDS)\n",
    "\n",
    "print COUNTS.most_common(10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "80029 the\n",
      "83 rare\n",
      "38312 and\n",
      "0 neverbeforeseen\n",
      "460 words\n"
     ]
    }
   ],
   "source": [
    "for w in tokens('the rare and neverbeforeseen words'):\n",
    "    print COUNTS[w], w"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In 1935, linguist George Zipf noted that in any big text, the *n*th most frequent word appears with a frequency of about 1/*n* of the most frequent word. He get's credit for *Zipf's Law*, even though Felix Auerbach made the same observation in 1913.  If we plot the frequency of words, most common first, on a log-log plot, they should come out as a straight line if Zipf's Law holds.  Here we see that it is a fairly close fit:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAX0AAAEPCAYAAACukxSbAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3XdYU9cbB/BvGA5GBUVBZYkgiIAoRRBEIuIoirTW2brY\ngnW0at0FHHXUqtSFyHLVtrQqtnWBCogVB2idFEVxD1woQ4ac3x/3RwQNECAkhLyf58mjNzn35s0h\nOXlz7rnn8BhjDIQQQuSCgrQDIIQQIjnU6BNCiByhRp8QQuQINfqEECJHqNEnhBA5Qo0+IYTIEWr0\nm6js7GyMHDkSmpqa2LBhQ4M8h4KCAm7evNkgx25IQUFB6NSpE+zt7aUdikzKzs6GgoICysrKGvy5\ngoODMX78+AZ/nve9/xrd3NywY8cOicfREGSy0Tc0NISKigrU1dWhrq6Ojz76CI8ePZJ2WI3Kzp07\n0apVKzx79gxfffVVvY/H5/MRGRkphsgajiiN0b1797Bx40akpaUhNTVVgtHVn6GhIY4dOybtMCSK\nx+NV+VhJSQlGjBiBTp06QUFBAUlJSULLmZqa4saNG/WK48CBA1L58mkIMtno83g8/PXXX3j9+jVe\nv36NV69eQUdHp1KZ0tJSKUXXOKSkpMDOzg4KCuL5E1f34WtsqrveMCUlBaampmjdurXQxxvz+4bH\n41X72hpCY64PAOjbty927twJHR0doe/RrKwslJWVwdjYWArRNU4y2ehXRUFBAdu3b0ePHj1gZmYG\nALh48SImT54MfX19zJw5E3fu3BGUv337Nvz8/KCjowNfX1+MGzc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Z2VmKkUledZ8PAJg4caK0QpO46t4Xn332Wa2O\n1WhO5BJCCGl4Em/0afqGd6gu3qG64FA9vEN18Y4460LijT5N3/AO1cU7VBccqod3qC7eEWtdiPOs\n8/vGjBnD2rdvz5o1a8Z0dXVZVFQUY4yxxMREZmZmxjp37sxCQ0MbMoRGg+riHaoLDtXDO1QX7zR0\nXdA0DIQQIkfoRC4hhMgRavQJIUSOUKNPCCFyhBp9QgiRI9ToE0KIHKFGnxBC5Ag1+oQQIkeo0SeE\nEDlCjT4hhMiR/wE9/sD6YxSWVQAAAABJRU5ErkJggg==\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x10fd46110>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "M = COUNTS['the']\n",
    "yscale('log'); xscale('log'); title('Frequency of n-th most frequent word and 1/n line.')\n",
    "plot([c for (w, c) in COUNTS.most_common()])\n",
    "plot([M/i for i in range(1, len(COUNTS)+1)]);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(3) Task: Spelling Correction\n",
    "========\n",
    "\n",
    "Given a word *w*, find the most likely correction *c* = `correct(`*w*`)`.\n",
    "\n",
    "**Approach:** Try all candidate words *c* that are known words that are near *w*.  Choose the most likely one.\n",
    "\n",
    "How to balance *near* and *likely*?\n",
    "\n",
    "For now, in a trivial way: always prefer nearer, but when there is a tie on nearness, use the word with the highest `WORDS` count.  Measure nearness by *edit distance*: the minimum number of deletions, transpositions, insertions, or replacements of characters. By trial and error, we determine that going out to edit distance 2 will give us reasonable results.  Then we can define `correct(`*w*`)`:\n",
    "        \n",
    "        \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def correct(word):\n",
    "    \"Find the best spelling correction for this word.\"\n",
    "    # Prefer edit distance 0, then 1, then 2; otherwise default to word itself.\n",
    "    candidates = (known(edits0(word)) or \n",
    "                  known(edits1(word)) or \n",
    "                  known(edits2(word)) or \n",
    "                  [word])\n",
    "    return max(candidates, key=COUNTS.get)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The functions `known` and `edits0` are easy; and `edits2` is easy if we assume we have `edits1`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def known(words):\n",
    "    \"Return the subset of words that are actually in the dictionary.\"\n",
    "    return {w for w in words if w in COUNTS}\n",
    "\n",
    "def edits0(word): \n",
    "    \"Return all strings that are zero edits away from word (i.e., just word itself).\"\n",
    "    return {word}\n",
    "\n",
    "def edits2(word):\n",
    "    \"Return all strings that are two edits away from this word.\"\n",
    "    return {e2 for e1 in edits1(word) for e2 in edits1(e1)}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now for `edits1(word)`: the set of candidate words that are one edit away. For example, given `\"wird\"`, this would include `\"weird\"` (inserting an `e`) and `\"word\"` (replacing a `i` with a `o`), and also `\"iwrd\"` (transposing `w` and `i`; then `known` can be used to filter this out of the set of final candidates). How could we get them?  One way is to *split* the original word in all possible places, each split forming a *pair* of words, `(a, b)`, before and after the place, and at each place, either delete, transpose, replace, or insert a letter:\n",
    "\n",
    "<table>\n",
    "  <tr><td> pairs: <td><tt> Ø+wird <td><tt> w+ird <td><tt> wi+rd <td><tt>wir+d<td><tt>wird+Ø<td><i>Notes:</i><tt> (<i>a</i>, <i>b</i>)</tt> pair</i>\n",
    "  <tr><td> deletions: <td><tt>Ø+ird<td><tt> w+rd<td><tt> wi+d<td><tt> wir+Ø<td><td><i>Delete first char of b</i>\n",
    "  <tr><td> transpositions: <td><tt>Ø+iwrd<td><tt> w+rid<td><tt> wi+dr</tt><td><td><td><i>Swap first two chars of b\n",
    "  <tr><td> replacements: <td><tt>Ø+?ird<td><tt> w+?rd<td><tt> wi+?d<td><tt> wir+?</tt><td><td><i>Replace char at start of b\n",
    "  <tr><td> insertions: <td><tt>Ø+?+wird<td><tt> w+?+ird<td><tt> wi+?+rd<td><tt> wir+?+d<td><tt> wird+?+Ø</tt><td><i>Insert char between a and b\n",
    "</table>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def edits1(word):\n",
    "    \"Return all strings that are one edit away from this word.\"\n",
    "    pairs      = splits(word)\n",
    "    deletes    = [a+b[1:]           for (a, b) in pairs if b]\n",
    "    transposes = [a+b[1]+b[0]+b[2:] for (a, b) in pairs if len(b) > 1]\n",
    "    replaces   = [a+c+b[1:]         for (a, b) in pairs for c in alphabet if b]\n",
    "    inserts    = [a+c+b             for (a, b) in pairs for c in alphabet]\n",
    "    return set(deletes + transposes + replaces + inserts)\n",
    "\n",
    "def splits(word):\n",
    "    \"Return a list of all possible (first, rest) pairs that comprise word.\"\n",
    "    return [(word[:i], word[i:]) \n",
    "            for i in range(len(word)+1)]\n",
    "\n",
    "alphabet = 'abcdefghijklmnopqrstuvwxyz'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('', 'wird'), ('w', 'ird'), ('wi', 'rd'), ('wir', 'd'), ('wird', '')]"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "splits('wird')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "set(['wird'])\n"
     ]
    }
   ],
   "source": [
    "print edits0('wird')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "set(['wirdh', 'wirdw', 'jird', 'wiid', 'wirj', 'wiprd', 'rird', 'wkird', 'wiqrd', 'wrird', 'wisrd', 'zwird', 'wiqd', 'wizrd', 'wirs', 'wrd', 'wqird', 'tird', 'wirdp', 'wrrd', 'wzrd', 'wiad', 'nird', 'wirsd', 'wixd', 'wxird', 'lird', 'eird', 'wmird', 'wihd', 'wirp', 'lwird', 'wirzd', 'widrd', 'wxrd', 'ewird', 'wirdx', 'wirkd', 'hwird', 'wipd', 'wirnd', 'uwird', 'wirz', 'mwird', 'wjrd', 'wirjd', 'wirrd', 'wirdd', 'wsird', 'bwird', 'wcrd', 'xwird', 'wdird', 'wibrd', 'wikd', 'wiryd', 'wiord', 'gird', 'wtird', 'wbrd', 'nwird', 'wlrd', 'wgird', 'wmrd', 'wirf', 'wirg', 'wird', 'wire', 'wirb', 'wirc', 'wira', 'wkrd', 'wiro', 'wirl', 'wirm', 'iird', 'wirk', 'wirh', 'wiri', 'wirv', 'wirw', 'wirt', 'wiru', 'wirr', 'wicd', 'cird', 'wirq', 'wirqd', 'wizd', 'wirhd', 'ird', 'bird', 'wirx', 'wiry', 'wvrd', 'widr', 'wprd', 'wirad', 'wijd', 'wirxd', 'uird', 'wirdb', 'qwird', 'dird', 'wnrd', 'wjird', 'gwird', 'whrd', 'wtrd', 'woird', 'rwird', 'wurd', 'wijrd', 'witrd', 'wwrd', 'dwird', 'vwird', 'wibd', 'wiyd', 'wicrd', 'weird', 'yird', 'wiwrd', 'wirdv', 'wirdu', 'wid', 'wirds', 'wirdr', 'sird', 'wirbd', 'wirdq', 'wirdy', 'wivrd', 'wirdg', 'wirdf', 'wirde', 'wiud', 'wirdc', 'wir', 'wirda', 'wfird', 'kwird', 'wirdn', 'wirdm', 'wirdl', 'wirdk', 'wirdj', 'wiird', 'wnird', 'wiurd', 'wied', 'aird', 'wirod', 'wpird', 'wcird', 'wzird', 'jwird', 'wirdo', 'wsrd', 'wimd', 'wirwd', 'mird', 'fird', 'wuird', 'wirdt', 'wired', 'wirgd', 'wirfd', 'witd', 'wfrd', 'wyrd', 'wihrd', 'zird', 'ward', 'wilrd', 'widd', 'iwrd', 'hird', 'word', 'wisd', 'wvird', 'pird', 'wlird', 'wyird', 'wdrd', 'werd', 'wild', 'oird', 'wirid', 'wgrd', 'wirvd', 'wiod', 'wirud', 'wircd', 'wiyrd', 'wigrd', 'wixrd', 'wiard', 'vird', 'wiwd', 'wigd', 'wirmd', 'swird', 'wierd', 'xird', 'qird', 'waird', 'wqrd', 'kird', 'cwird', 'wirtd', 'wirdz', 'awird', 'fwird', 'wirpd', 'wifrd', 'pwird', 'owird', 'wivd', 'wimrd', 'iwird', 'winrd', 'wirdi', 'wrid', 'wifd', 'wirld', 'wwird', 'ywird', 'wirn', 'wbird', 'whird', 'wikrd', 'wind', 'twird'])\n"
     ]
    }
   ],
   "source": [
    "print edits1('wird')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "24254\n"
     ]
    }
   ],
   "source": [
    "print len(edits2('wird'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['spelling',\n",
       " 'errors',\n",
       " 'in',\n",
       " 'something',\n",
       " 'whatever',\n",
       " 'unusual',\n",
       " 'mistakes',\n",
       " 'everywhere']"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "map(correct, tokens('Speling errurs in somethink. Whutever; unusuel misteakes everyware?'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Can we make the output prettier than that?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def correct_text(text):\n",
    "    \"Correct all the words within a text, returning the corrected text.\"\n",
    "    return re.sub('[a-zA-Z]+', correct_match, text)\n",
    "\n",
    "def correct_match(match):\n",
    "    \"Spell-correct word in match, and preserve proper upper/lower/title case.\"\n",
    "    word = match.group()\n",
    "    return case_of(word)(correct(word.lower()))\n",
    "\n",
    "def case_of(text):\n",
    "    \"Return the case-function appropriate for text: upper, lower, title, or just str.\"\n",
    "    return (str.upper if text.isupper() else\n",
    "            str.lower if text.islower() else\n",
    "            str.title if text.istitle() else\n",
    "            str)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[<method 'upper' of 'str' objects>,\n",
       " <method 'lower' of 'str' objects>,\n",
       " <method 'title' of 'str' objects>,\n",
       " str]"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "map(case_of, ['UPPER', 'lower', 'Title', 'CamelCase'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Spelling Errors IN something. Whatever; unusual mistakes?'"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "correct_text('Speling Errurs IN somethink. Whutever; unusuel misteakes?')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Audience says: tumbler ...'"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "correct_text('Audiance sayzs: tumblr ...')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So far so good.  You can probably think of a dozen ways to make this better.  Here's one: in the text \"three, too, one, blastoff!\" we might want to correct \"too\" with \"two\", even though \"too\" is in the dictionary.  We can do better if we look at a *sequence* of words, not just an individual word one at a time.  But how can we choose the best corrections of a sequence?  The ad-hoc approach worked pretty well for single words, but now we could use some real theory ..."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(4) Models: Word and Sequence Probabilities\n",
    "===\n",
    "\n",
    "If we have a bag of words, what's the probability of picking a particular word out of the bag? We'll denote that probability as $P(w)$.  To create the function `P` that computes this probability, we define a function, `pdist`, that takes as input a `Counter` (that is, a bag of words) and returns a function that acts as a probability distribution over all possible words.  In a probability distribution the probability of each word is between 0 and 1, and the sum of the probabilities is 1."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def pdist(counter):\n",
    "    \"Make a probability distribution, given evidence from a Counter.\"\n",
    "    N = sum(counter.values())\n",
    "    return lambda x: counter[x]/N\n",
    "\n",
    "Pword = pdist(COUNTS)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.0724106075672 the\n",
      "0.00884356018896 is\n",
      "0.000821562579453 most\n",
      "0.000259678921039 common\n",
      "0.000269631771671 word\n",
      "0.0199482270806 in\n",
      "0.000190913771217 english\n"
     ]
    }
   ],
   "source": [
    "# Print probabilities of some words\n",
    "for w in tokens('\"The\" is most common word in English'):\n",
    "    print Pword(w), w"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, what is the probability of a *sequence* of words?  Use the definition of a joint probability:\n",
    "\n",
    "$P(w_1 \\ldots w_n) = P(w_1) \\times P(w_2 \\mid w_1) \\times P(w_3 \\mid w_1 w_2) \\ldots  \\times \\ldots P(w_n \\mid w_1 \\ldots w_{n-1})$\n",
    "\n",
    "In the bag of words model, each word is drawn from the bag *independently* of the others.  So $P(w_2 \\mid w_1) = P(w_2)$, and we have:\n",
    "    \n",
    "$P(w_1 \\ldots w_n) = P(w_1) \\times P(w_2) \\times P(w_3) \\ldots  \\times \\ldots P(w_n)$\n",
    "\n",
    "    \n",
    "<img src=\"http://upload.wikimedia.org/wikipedia/commons/thumb/a/a2/GeorgeEPBox.jpg/200px-GeorgeEPBox.jpg\"> \n",
    "\n",
    "Now clearly this model is wrong; the probability of a sequence depends on the order of the words.  But, as the statistician George Box said,  *All models are wrong, but some are useful.*  The bag of words model, wrong as it is, has many useful applications.\n",
    "    \n",
    "How can we compute $P(w_1 \\ldots w_n)$?  We'll use a different function name, `Pwords`, rather than `P`, and we compute the product of the individual probabilities:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def Pwords(words):\n",
    "    \"Probability of words, assuming each word is independent of others.\"\n",
    "    return product(Pword(w) for w in words)\n",
    "\n",
    "def product(nums):\n",
    "    \"Multiply the numbers together.  (Like `sum`, but with multiplication.)\"\n",
    "    result = 1\n",
    "    for x in nums:\n",
    "        result *= x\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2.98419543271e-11 this is a test\n",
      "8.64036404331e-16 this is a unusual test\n",
      "0.0 this is a neverbeforeseen test\n"
     ]
    }
   ],
   "source": [
    "tests = ['this is a test', \n",
    "         'this is a unusual test',\n",
    "         'this is a neverbeforeseen test']\n",
    "\n",
    "for test in tests:\n",
    "    print Pwords(tokens(test)), test"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Yikes&mdash;it seems wrong to give a probability of 0 to the last one; it should just be very small.  We'll come back to that later.  The other probabilities seem reasonable."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(5) Task: Word Segmentation\n",
    "====\n",
    "\n",
    "**Task**: *given a sequence of characters with no spaces separating words, recover the sequence of words.*\n",
    "   \n",
    "\n",
    "Why? Languages with no word delimiters: [不带空格的词](http://translate.google.com/#auto/en/%E4%B8%8D%E5%B8%A6%E7%A9%BA%E6%A0%BC%E7%9A%84%E8%AF%8D)\n",
    "\n",
    "In English, sub-genres with no word delimiters ([spelling errors](https://www.google.com/search?q=wordstogether), [URLs](http://speedofart.com)).\n",
    "\n",
    "**Approach 1:** Enumerate all candidate segementations and choose the one with highest Pwords\n",
    "\n",
    "Problem: how many segmentations are there for an *n*-character text?\n",
    "\n",
    "**Approach 2:** Make one segmentation, into a first word and remaining characters.  If we assume words are independent \n",
    "then we can maximize the probability of the first word adjoined to the best segmentation of the remaining characters.\n",
    "    \n",
    "    assert segment('choosespain') == ['choose', 'spain']\n",
    "\n",
    "    segment('choosespain') ==\n",
    "       max(Pwords(['c'] + segment('hoosespain')),\n",
    "           Pwords(['ch'] + segment('oosespain')),\n",
    "           Pwords(['cho'] + segment('osespain')),\n",
    "           Pwords(['choo'] + segment('sespain')),\n",
    "           ...\n",
    "           Pwords(['choosespain'] + segment('')))\n",
    "       \n",
    "    \n",
    "       \n",
    "To make this somewhat efficient, we need to avoid re-computing the segmentations of the remaining characters.  This can be done explicitly by *dynamic programming* or implicitly with *memoization*. Also, we shouldn't consider all possible lengths for the first word; we can impose a maximum length.  What should it be?  A little more than the longest word seen so far."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def memo(f):\n",
    "    \"Memoize function f, whose args must all be hashable.\"\n",
    "    cache = {}\n",
    "    def fmemo(*args):\n",
    "        if args not in cache:\n",
    "            cache[args] = f(*args)\n",
    "        return cache[args]\n",
    "    fmemo.cache = cache\n",
    "    return fmemo"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "18"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "max(len(w) for w in COUNTS)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def splits(text, start=0, L=20):\n",
    "    \"Return a list of all (first, rest) pairs; start <= len(first) <= L.\"\n",
    "    return [(text[:i], text[i:]) \n",
    "            for i in range(start, min(len(text), L)+1)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('', 'word'), ('w', 'ord'), ('wo', 'rd'), ('wor', 'd'), ('word', '')]\n",
      "[('r', 'eallylongtext'), ('re', 'allylongtext'), ('rea', 'llylongtext'), ('real', 'lylongtext')]\n"
     ]
    }
   ],
   "source": [
    "print splits('word')\n",
    "print splits('reallylongtext', 1, 4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "@memo\n",
    "def segment(text):\n",
    "    \"Return a list of words that is the most probable segmentation of text.\"\n",
    "    if not text: \n",
    "        return []\n",
    "    else:\n",
    "        candidates = ([first] + segment(rest) \n",
    "                      for (first, rest) in splits(text, 1))\n",
    "        return max(candidates, key=Pwords)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['choose', 'spain']"
      ]
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "segment('choosespain')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['speed', 'of', 'art']"
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "segment('speedofart')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "decl = ('wheninthecourseofhumaneventsitbecomesnecessaryforonepeople' +\n",
    "        'todissolvethepoliticalbandswhichhaveconnectedthemwithanother' +\n",
    "        'andtoassumeamongthepowersoftheearththeseparateandequalstation' +\n",
    "        'towhichthelawsofnatureandofnaturesgodentitlethem')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "when in the course of human events it becomes necessary for one people to dissolve the political bands which have connected them with another and to assume among the powers of the earth the separate and equal station to which the laws of nature and of natures god entitle them\n"
     ]
    }
   ],
   "source": [
    "print(' '.join(segment(decl)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3.613815636889254e-141"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Pwords(segment(decl))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1.305966345742529e-281"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Pwords(segment(decl+decl))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.0"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Pwords(segment(decl+decl+decl))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That's a problem.  We'll come back to it later."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['small', 'and', 'insignificant']"
      ]
     },
     "execution_count": 50,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "segment('smallandinsignificant')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['large', 'and', 'insignificant']"
      ]
     },
     "execution_count": 51,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "segment('largeandinsignificant')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4.1121373609e-10\n",
      "1.06638804821e-11\n"
     ]
    }
   ],
   "source": [
    "print(Pwords(['large', 'and', 'insignificant']))\n",
    "print(Pwords(['large', 'and', 'in', 'significant']))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Summary:\n",
    "    \n",
    "- Looks pretty good!\n",
    "- The bag-of-words assumption is a limitation.\n",
    "- Recomputing Pwords on each recursive call is somewhat inefficient.\n",
    "- Numeric underflow for texts longer than 100 or so words; we'll need to use logarithms, or other tricks.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# (6) Data: Mo' Data, Mo' Better"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's move up from millions to *billions and billions* of words.  Once we have that amount of data, we can start to look at two word sequences, without them being too sparse.  I happen to have data files available in the format of `\"word \\t count\"`, and bigram data in the form of `\"word1 word2 \\t count\"`.  Let's arrange to read them in:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def load_counts(filename, sep='\\t'):\n",
    "    \"\"\"Return a Counter initialized from key-value pairs, \n",
    "    one on each line of filename.\"\"\"\n",
    "    C = Counter()\n",
    "    for line in open(filename):\n",
    "        key, count = line.split(sep)\n",
    "        C[key] = int(count)\n",
    "    return C"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "COUNTS1 = load_counts('count_1w.txt')\n",
    "COUNTS2 = load_counts('count_2w.txt')\n",
    "\n",
    "P1w = pdist(COUNTS1)\n",
    "P2w = pdist(COUNTS2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "333333 588.124220187\n",
      "286358 225.955251755\n"
     ]
    }
   ],
   "source": [
    "print len(COUNTS1), sum(COUNTS1.values())/1e9\n",
    "print len(COUNTS2), sum(COUNTS2.values())/1e9"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('of the', 2766332391),\n",
       " ('in the', 1628795324),\n",
       " ('to the', 1139248999),\n",
       " ('on the', 800328815),\n",
       " ('for the', 692874802),\n",
       " ('and the', 629726893),\n",
       " ('to be', 505148997),\n",
       " ('is a', 476718990),\n",
       " ('with the', 461331348),\n",
       " ('from the', 428303219),\n",
       " ('by the', 417106045),\n",
       " ('at the', 416201497),\n",
       " ('of a', 387060526),\n",
       " ('in a', 364730082),\n",
       " ('will be', 356175009),\n",
       " ('that the', 333393891),\n",
       " ('do not', 326267941),\n",
       " ('is the', 306482559),\n",
       " ('to a', 279146624),\n",
       " ('is not', 276753375),\n",
       " ('for a', 274112498),\n",
       " ('with a', 271525283),\n",
       " ('as a', 270401798),\n",
       " ('<S> and', 261891475),\n",
       " ('of this', 258707741),\n",
       " ('<S> the', 258483382),\n",
       " ('it is', 245002494),\n",
       " ('can be', 230215143),\n",
       " ('If you', 210252670),\n",
       " ('has been', 196769958)]"
      ]
     },
     "execution_count": 56,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "COUNTS2.most_common(30)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(7) Theory and Practice: Segmentation With Bigram Data\n",
    "===\n",
    "\n",
    "A less-wrong approximation:\n",
    "    \n",
    "$P(w_1 \\ldots w_n) = P(w_1 \\mid start) \\times P(w_2 \\mid w_1) \\times P(w_3 \\mid w_2) \\ldots  \\times \\ldots P(w_n \\mid w_{n-1})$\n",
    "\n",
    "This is called the *bigram* model, and is equivalent to taking a text, cutting it up into slips of paper with two words on them, and having multiple bags, and putting each slip into a bag labelled with the first word on the slip.  Then, to generate language, we choose the first word from the original single bag of words, and chose all subsequent words from the bag with the label of the previously-chosen word. To determine the probability of a word sequence, we multiply together the conditional probabilities of each word given the previous word.  We'll do this with a function, `cPword` for \"conditional probability of a word.\"\n",
    "\n",
    "$P(w_n \\mid w_{n-1}) = P(w_{n-1}w_n) / P(w_{n-1}) $"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def Pwords2(words, prev='<S>'):\n",
    "    \"The probability of a sequence of words, using bigram data, given prev word.\"\n",
    "    return product(cPword(w, (prev if (i == 0) else words[i-1]) )\n",
    "                   for (i, w) in enumerate(words))\n",
    "\n",
    "P = P1w # Use the big dictionary for the probability of a word\n",
    "\n",
    "def cPword(word, prev):\n",
    "    \"Conditional probability of word, given previous word.\"\n",
    "    bigram = prev + ' ' + word\n",
    "    if P2w(bigram) > 0 and P(prev) > 0:\n",
    "        return P2w(bigram) / P(prev)\n",
    "    else: # Average the back-off value and zero.\n",
    "        return P(word) / 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2.98419543271e-11\n",
      "6.41367629438e-08\n",
      "1.18028600367e-11\n"
     ]
    }
   ],
   "source": [
    "print Pwords(tokens('this is a test'))\n",
    "print Pwords2(tokens('this is a test'))\n",
    "print Pwords2(tokens('is test a this'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To make `segment2`, we copy `segment`, and make sure to pass around the previous token, and to evaluate probabilities with `Pwords2` instead of `Pwords`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "@memo \n",
    "def segment2(text, prev='<S>'): \n",
    "    \"Return best segmentation of text; use bigram data.\" \n",
    "    if not text: \n",
    "        return []\n",
    "    else:\n",
    "        candidates = ([first] + segment2(rest, first) \n",
    "                      for (first, rest) in splits(text, 1))\n",
    "        return max(candidates, key=lambda words: Pwords2(words, prev))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['choose', 'spain']\n",
      "['speed', 'of', 'art']\n",
      "['small', 'and', 'in', 'significant']\n",
      "['large', 'and', 'in', 'significant']\n"
     ]
    }
   ],
   "source": [
    "print segment2('choosespain')\n",
    "print segment2('speedofart')\n",
    "print segment2('smallandinsignificant')\n",
    "print segment2('largeandinsignificant')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['far', 'out', 'in', 'the', 'un', 'chart', 'ed', 'back', 'waters', 'of', 'the', 'un', 'fashionable', 'end', 'of', 'the', 'western', 'spiral', 'arm', 'of', 'the', 'galaxy', 'lies', 'a', 'small', 'un', 'regarded', 'yellow', 'sun']\n",
      "['far', 'out', 'in', 'the', 'uncharted', 'backwaters', 'of', 'the', 'unfashionable', 'end', 'of', 'the', 'western', 'spiral', 'arm', 'of', 'the', 'galaxy', 'lies', 'a', 'small', 'un', 'regarded', 'yellow', 'sun']\n"
     ]
    }
   ],
   "source": [
    "adams = ('faroutintheunchartedbackwatersoftheunfashionableendofthewesternspiral' +\n",
    "         'armofthegalaxyliesasmallunregardedyellowsun')\n",
    "print segment(adams)\n",
    "print segment2(adams)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.0"
      ]
     },
     "execution_count": 62,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "P1w('unregarded')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['a', 'dry', 'bare', 'sandy', 'hole', 'with', 'nothing', 'in', 'it', 'to', 'sit', 'down', 'on', 'or', 'to', 'eat']\n",
      "['a', 'dry', 'bare', 'sandy', 'hole', 'with', 'nothing', 'in', 'it', 'to', 'sit', 'down', 'on', 'or', 'to', 'eat']\n"
     ]
    }
   ],
   "source": [
    "tolkein = 'adrybaresandyholewithnothinginittositdownonortoeat'\n",
    "print segment(tolkein)\n",
    "print segment2(tolkein)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Conclusion? Bigram model is a little better, but not much.  Hundreds of billions of words still not enough. (Why not trillions?) Could be made more efficient."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(8) Theory: Evaluation\n",
    "===\n",
    "\n",
    "So far, we've got an intuitive feel for how this all works.  But we don't have any solid metrics that quantify the results.  Without metrics, we can't say if we are doing well, nor if a change is an improvement. In general,\n",
    "when developing a program that relies on data to help make\n",
    "predictions, it is good practice to divide your data into three sets:\n",
    "<ol>\n",
    "  <li> <b>Training set:</b> the data used to create our spelling\n",
    "  model; this was the <tt>big.txt</tt> file.\n",
    "  <li> <b>Development set:</b> a set of input/output pairs that we can\n",
    "  use to rank the performance of our program as we are developing it.\n",
    "  <li> <b>Test set:</b> another set of input/output pairs that we use\n",
    "  to rank our program <i>after</i> we are done developing it.  The\n",
    "  development set can't be used for this purpose&mdash;once the\n",
    "  programmer has looked at the development test it is tainted, because\n",
    "  the programmer might modify the program just to pass the development\n",
    "  test.  That's why we need a separate test set that is only looked at\n",
    "  after development is done.\n",
    "</ol>\n",
    "\n",
    "For this program, the training data is the word frequency counts, the development set is the examples like `\"choosespain\"` that we have been playing with, and now we need a test set."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def test_segmenter(segmenter, tests):\n",
    "    \"Try segmenter on tests; report failures; return fraction correct.\"\n",
    "    return sum([test_one_segment(segmenter, test) \n",
    "               for test in tests]), len(tests)\n",
    "\n",
    "def test_one_segment(segmenter, test):\n",
    "    words = tokens(test)\n",
    "    result = segmenter(cat(words))\n",
    "    correct = (result == words)\n",
    "    if not correct:\n",
    "        print 'expected', words\n",
    "        print '     got', result\n",
    "    return correct\n",
    "\n",
    "cat = ''.join\n",
    "\n",
    "proverbs = (\"\"\"A little knowledge is a dangerous thing\n",
    "  A man who is his own lawyer has a fool for his client\n",
    "  All work and no play makes Jack a dull boy\n",
    "  Better to remain silent and be thought a fool that to speak and remove all doubt;\n",
    "  Do unto others as you would have them do to you\n",
    "  Early to bed and early to rise, makes a man healthy, wealthy and wise\n",
    "  Fools rush in where angels fear to tread\n",
    "  Genius is one percent inspiration, ninety-nine percent perspiration\n",
    "  If you lie down with dogs, you will get up with fleas\n",
    "  Lightning never strikes twice in the same place\n",
    "  Power corrupts; absolute power corrupts absolutely\n",
    "  Here today, gone tomorrow\n",
    "  See no evil, hear no evil, speak no evil\n",
    "  Sticks and stones may break my bones, but words will never hurt me\n",
    "  Take care of the pence and the pounds will take care of themselves\n",
    "  Take care of the sense and the sounds will take care of themselves\n",
    "  The bigger they are, the harder they fall\n",
    "  The grass is always greener on the other side of the fence\n",
    "  The more things change, the more they stay the same\n",
    "  Those who do not learn from history are doomed to repeat it\"\"\"\n",
    "  .splitlines())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "expected ['power', 'corrupts', 'absolute', 'power', 'corrupts', 'absolutely']\n",
      "     got ['power', 'corrupt', 's', 'absolute', 'power', 'corrupt', 's', 'absolutely']\n",
      "expected ['the', 'grass', 'is', 'always', 'greener', 'on', 'the', 'other', 'side', 'of', 'the', 'fence']\n",
      "     got ['the', 'grass', 'is', 'always', 'green', 'er', 'on', 'the', 'other', 'side', 'of', 'the', 'fence']\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(18, 20)"
      ]
     },
     "execution_count": 70,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "test_segmenter(segment, proverbs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(20, 20)"
      ]
     },
     "execution_count": 68,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "test_segmenter(segment2, proverbs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This confirms that both segmenters are very good, and that `segment2` is slightly better. There is much more that can be done in terms of the variety of tests, and in measuring statistical significance."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(9) Theory and Practice: Smoothing\n",
    "======\n",
    "\n",
    "Let's go back to a test we did before, and add some more test cases:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2.98419543271e-11 this is a test\n",
      "8.64036404331e-16 this is a unusual test\n",
      "0.0 this is a nongovernmental test\n",
      "0.0 this is a neverbeforeseen test\n",
      "0.0 this is a zqbhjhsyefvvjqc test\n"
     ]
    }
   ],
   "source": [
    "tests = ['this is a test', \n",
    "         'this is a unusual test',\n",
    "         'this is a nongovernmental test',\n",
    "         'this is a neverbeforeseen test',\n",
    "         'this is a zqbhjhsyefvvjqc test']\n",
    "\n",
    "for test in tests:\n",
    "    print Pwords(tokens(test)), test"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The issue here is the finality of a probability of zero.  Out of the three 15-letter words, it turns out that \"nongovernmental\" is in the dictionary, but if it hadn't been, if somehow our corpus of words had missed it, then the probability of that whole phrase would have been zero.  It seems that is too strict; there must be some \"real\" words that are not in our dictionary, so we shouldn't give them probability zero.  There is also a question of likelyhood of being a \"real\" word.  It does seem that \"neverbeforeseen\" is more English-like than \"zqbhjhsyefvvjqc\", and so perhaps should have a higher probability.\n",
    "\n",
    "We can address this by assigning a non-zero probability to words that are not in the dictionary.  This is even more important when it comes to multi-word phrases (such as bigrams), because it is more likely that a legitimate one will appear that has not been observed before.\n",
    "\n",
    "We can think of our model as being overly spiky; it has a spike of probability mass wherever a word or phrase occurs in the corpus.  What we would like to do is *smooth* over those spikes so that we get a model that does not depend on the details of our corpus. The process of \"fixing\" the model is called *smoothing*.\n",
    "\n",
    "For example, Laplace was asked what's the probability of the sun rising tomorrow.  From data that it has risen $n/n$ times for the last *n* days, the maximum liklihood estimator is 1.  But Laplace wanted to balance the data with the possibility that tomorrow, either it will rise or it won't, so he came up with $(n + 1) / (n + 2)$.\n",
    "\n",
    "\n",
    "<img src=\"http://upload.wikimedia.org/wikipedia/commons/thumb/e/e3/Pierre-Simon_Laplace.jpg/220px-Pierre-Simon_Laplace.jpg\" height=150 width=110> \n",
    "&nbsp;\n",
    "<img src=\"http://www.hdwallpapers.in/walls/notre_dame_at_sunrise_paris_france-normal.jpg\" width=200 height=150>\n",
    "<br><i>What we know is little, and what we are ignorant of is immense.<i><br>&mdash; Pierre Simon Laplace, 1749-1827"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def pdist_additive_smoothed(counter, c=1):\n",
    "    \"\"\"The probability of word, given evidence from the counter.\n",
    "    Add c to the count for each item, plus the 'unknown' item.\"\"\"\n",
    "    N = sum(counter.values())          # Amount of evidence\n",
    "    Nplus = N + c * (len(counter) + 1) # Evidence plus fake observations\n",
    "    return lambda word: (counter[word] + c) / Nplus \n",
    "\n",
    "P1w = pdist_additive_smoothed(COUNTS1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1.7003201005861308e-12"
      ]
     },
     "execution_count": 74,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "P1w('neverbeforeseen')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "But now there's a problem ... we now have previously-unseen words with non-zero probabilities.  And maybe 10<sup>-12</sup> is about right for words that are observed in text: that is, if I'm *reading* a new text, the probability that the next word is unknown might be around 10<sup>-12</sup>.  But if I'm *manufacturing* 20-letter sequences at random, the probability that one will be a word is much, much lower than 10<sup>-12</sup>.  \n",
    "\n",
    "Look what happens:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['this',\n",
       " 'is',\n",
       " 'a',\n",
       " 'test',\n",
       " 'of',\n",
       " 'segment',\n",
       " 'at',\n",
       " 'i',\n",
       " 'on',\n",
       " 'of',\n",
       " 'along',\n",
       " 'sequence',\n",
       " 'of',\n",
       " 'words']"
      ]
     },
     "execution_count": 75,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "segment.cache.clear()\n",
    "segment('thisisatestofsegmentationofalongsequenceofwords')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There are two problems:\n",
    "    \n",
    "First, we don't have a clear model of the unknown words.  We just say \"unknown\" but\n",
    "we don't distinguish likely unknown from unlikely unknown.  For example, is a 8-character unknown more likely than a 20-character unknown?\n",
    "\n",
    "Second, we don't take into account evidence from *parts* of the unknown.  For example, \n",
    "\"unglobulate\" versus \"zxfkogultae\".\n",
    "\n",
    "For our next approach, *Good - Turing* smoothing re-estimates the probability of zero-count words, based on the probability of one-count words (and can also re-estimate for higher-number counts, but that is less interesting).\n",
    "\n",
    "<img src=\"http://upload.wikimedia.org/wikipedia/en/b/b4/I._J._Good.jpg\">\n",
    "<img src=\"http://upload.wikimedia.org/wikipedia/en/thumb/c/c8/Alan_Turing_photo.jpg/200px-Alan_Turing_photo.jpg\" height=144>\n",
    "<br><i>I. J. Good (1916 - 2009) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Alan Turing (1812 - 1954)</i>\n",
    "\n",
    "So, how many one-count words are there in `COUNTS`?  (There aren't any in `COUNTS1`.)  And what are the word lengths of them?  Let's find out:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[(7, 1357),\n",
       " (8, 1356),\n",
       " (9, 1176),\n",
       " (6, 1113),\n",
       " (10, 938),\n",
       " (5, 747),\n",
       " (11, 627),\n",
       " (12, 398),\n",
       " (4, 367),\n",
       " (13, 215),\n",
       " (3, 161),\n",
       " (14, 112),\n",
       " (2, 51),\n",
       " (15, 37),\n",
       " (16, 10),\n",
       " (17, 7)]"
      ]
     },
     "execution_count": 76,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "singletons = (w for w in COUNTS if COUNTS[w] == 1)\n",
    "\n",
    "lengths = map(len, singletons)\n",
    "\n",
    "Counter(lengths).most_common()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.0012278198461651215"
      ]
     },
     "execution_count": 77,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "1357 / sum(COUNTS.values())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 78,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAX4AAAEACAYAAAC08h1NAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAG+RJREFUeJzt3X9MFGfiP/D3bihorouHemIT3GKV7g9/AQpLNchq/EGT\no3AagzZeG8HE485DLdd4UROhyVeDaCyYshLv1qZtrNc0aWq1iMLdqOTOXajN9Sr4Aw8PSE5RaGUR\nqBaf7x98uqeCyC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G3/zm\nN8jOzn7sNrop/rt372L58uX49a9/jfT0dK3j9PP3v/8dR44cweTJk7Fq1Sr89a9/xRtvvKF1rH6m\nTp0Ki8WCtLQ0jB49GqtWrUJ5ebnWsfrxer1ISkrC1KlTMW7cOKxYsQKnT5/WOtYjJSQk+J80q6+v\nR0JCgsaJHu39999HRUUFPvroI62j9HPlyhVcvXoVs2bNwuTJk9HS0oLZs2ejtbVV62j9JCUlITMz\nE6NHj0ZaWhouXLigy/+eq6urkZWVhZCQEGRnZw/pcaSL4hdCIDs7G9OnT9fV2R3327FjB5qbm9HY\n2IjDhw9j4cKF+OCDD7SONaCYmBh4PB7cu3cPx44dw6JFi7SO1E9ycjJqa2vR3t6OH374AeXl5Viy\nZInWsR7J4XDA7Xaju7sbbrcbSUlJWkca0PHjx1FUVIQjR45g1KhRWsfpZ8aMGbh+/ToaGxvR2NiI\nqKgonDt3DhMmTNA6Wj+vvPIKysvLIYSAx+PBlClTdPkzXbBgAY4cOQKgbxpt8eLFj99I/eedA3fm\nzBlhMBjErFmzRGxsrIiNjRXl5eVax3okRVF0fVbPxYsXhcPhELNmzRJ5eXmis7NT60gDOnjwoJg/\nf76YM2eO2LZtm+jt7dU6khBCiJUrV4oXXnhBhIaGiqioKOF2u0VHR4d47bXXxKRJk0R6errw+Xxa\nx/TnfO6550RUVJT485//LKZOnSrMZrP/cZSTk6OLjPf/LO83efJkXZzVM1DOH3/8Uaxbt05YrVaR\nkZEhvF6v1jH7/c7dbrf49ttvxcqVK8XMmTPF66+/Lurr6x87Dl/ARUQkGV1M9RAR0chh8RMRSYbF\nT0QkGRY/EZFkWPxERJJh8RMRSYbFT0QkGRY/EZFk/j/40bg2F6Di4wAAAABJRU5ErkJggg==\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x114504210>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "hist(lengths, bins=len(set(lengths)));"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def pdist_good_turing_hack(counter, onecounter, base=1/26., prior=1e-8):\n",
    "    \"\"\"The probability of word, given evidence from the counter.\n",
    "    For unknown words, look at the one-counts from onecounter, based on length.\n",
    "    This gets ideas from Good-Turing, but doesn't implement all of it.\n",
    "    prior is an additional factor to make unknowns less likely.\n",
    "    base is how much we attenuate probability for each letter beyond longest.\"\"\"\n",
    "    N = sum(counter.values())\n",
    "    N2 = sum(onecounter.values())\n",
    "    lengths = map(len, [w for w in onecounter if onecounter[w] == 1])\n",
    "    ones = Counter(lengths)\n",
    "    longest = max(ones)\n",
    "    return (lambda word: \n",
    "            counter[word] / N if (word in counter) \n",
    "            else prior * (ones[len(word)] / N2 or \n",
    "                          ones[longest] / N2 * base ** (len(word)-longest)))\n",
    "\n",
    "# Redefine P1w\n",
    "P1w = pdist_good_turing_hack(COUNTS1, COUNTS)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 80,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['this',\n",
       " 'is',\n",
       " 'a',\n",
       " 'test',\n",
       " 'of',\n",
       " 'segment',\n",
       " 'at',\n",
       " 'i',\n",
       " 'on',\n",
       " 'of',\n",
       " 'a',\n",
       " 'very',\n",
       " 'long',\n",
       " 'sequence',\n",
       " 'of',\n",
       " 'words']"
      ]
     },
     "execution_count": 80,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "segment.cache.clear()\n",
    "segment('thisisatestofsegmentationofaverylongsequenceofwords')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That was somewhat unsatisfactory.  We really had to crank up the prior, specifically because the process of running `segment` generates so many non-word candidates (and also because there will be fewer unknowns with respect to the billion-word `WORDS1` than with respect to the million-word `WORDS`).  It would be better to separate out the prior from the word distribution, so that the same distribution could be used for multiple tasks, not just for this one.\n",
    "\n",
    "Now let's think for a short while about smoothing **bigram** counts.  Specifically, what if we haven't seen a bigram sequence, but we've seen both words individually?  For example, to evaluate P(\"Greenland\") in the phrase \"turn left at Greenland\", we might have three pieces of evidence:\n",
    "\n",
    "    P(\"Greenland\")\n",
    "    P(\"Greenland\" | \"at\")\n",
    "    P(\"Greenland\" | \"left\", \"at\")\n",
    "    \n",
    "Presumably, the first would have a relatively large count, and thus large reliability, while the second and third would have decreasing counts and reliability.  With *interpolation smoothing* we combine all three pieces of evidence, with a linear combination:\n",
    "    \n",
    "$P(w_3 \\mid w_1w_2) = c_1 P(w_3) + c_2 P(w_3 \\mid w_2) + c_3 P(w_3 \\mid w_1w_2)$\n",
    "\n",
    "How do we choose $c_1, c_2, c_3$?  By experiment: train on training data, maximize $c$ values on development data, then evaluate on test data.\n",
    "    \n",
    "However, when we do this, we are saying, with probability $c_1$, that a word can appear anywhere, regardless of previous words.  But some words are more free to do that than other words.  Consider two words with similar probability:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "7.73314623661e-05\n",
      "7.72494966889e-05\n"
     ]
    }
   ],
   "source": [
    "print P1w('francisco')\n",
    "print P1w('individuals')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "They have similar unigram probabilities but differ in their freedom to be the second word of a bigram:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['San francisco', 'san francisco']\n"
     ]
    }
   ],
   "source": [
    "print [bigram for bigram in COUNTS2 if bigram.endswith('francisco')]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['are individuals', 'other individuals', 'on individuals', 'infected individuals', 'in individuals', 'where individuals', 'or individuals', 'which individuals', 'to individuals', 'both individuals', 'help individuals', 'more individuals', 'interested individuals', 'from individuals', '<S> individuals', 'income individuals', 'these individuals', 'about individuals', 'the individuals', 'among individuals', 'some individuals', 'those individuals', 'by individuals', 'minded individuals', 'These individuals', 'qualified individuals', 'certain individuals', 'different individuals', 'For individuals', 'few individuals', 'and individuals', 'two individuals', 'for individuals', 'between individuals', 'affected individuals', 'healthy individuals', 'private individuals', 'with individuals', 'following individuals', 'as individuals', 'such individuals', 'that individuals', 'all individuals', 'of individuals', 'many individuals']\n"
     ]
    }
   ],
   "source": [
    "print [bigram for bigram in COUNTS2 if bigram.endswith('individuals')]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Intuitively, words that appear in many bigrams before are more likely to appear in a new, previously unseen bigram. In *Kneser-Ney* smoothing (Reinhard Kneser, Hermann Ney) we multiply the bigram counts by this ratio.  But I won't implement that here, because The Count never covered it.\n",
    "\n",
    "(10) One More Task: Secret Codes\n",
    "===\n",
    "\n",
    "Let's tackle one more task: decoding secret codes.  We'll start with the simplest of codes, a rotation cipher, sometimes called a shift cipher or a Caesar cipher (because this was state-of-the-art crypotgraphy in 100 BC).  First, a method to encode:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 96,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def rot(msg, n=13): \n",
    "    \"Encode a message with a rotation (Caesar) cipher.\" \n",
    "    return encode(msg, alphabet[n:]+alphabet[:n])\n",
    "\n",
    "def encode(msg, key): \n",
    "    \"Encode a message with a substitution cipher.\" \n",
    "    table = string.maketrans(upperlower(alphabet), upperlower(key))\n",
    "    return msg.translate(table) \n",
    "\n",
    "def upperlower(text): return text.upper() + text.lower()  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Uijt jt b tfdsfu nfttbhf.'"
      ]
     },
     "execution_count": 97,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "rot('This is a secret message.', 1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 98,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Guvf vf n frperg zrffntr.'"
      ]
     },
     "execution_count": 98,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "rot('This is a secret message.', 13)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 99,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'This is a secret message.'"
      ]
     },
     "execution_count": 99,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "rot(rot('This is a secret message.'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now decoding is easy: try all 26 candidates, and find the one with the maximum Pwords:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 101,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def decode_rot(secret):\n",
    "    \"Decode a secret message that has been encoded with a rotation cipher.\"\n",
    "    candidates = [rot(secret, i) for i in range(len(alphabet))]\n",
    "    return max(candidates, key=lambda msg: Pwords(tokens(msg)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 102,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Nyf befnj kyv rejnvi?\n",
      "Who knows the answer?\n"
     ]
    }
   ],
   "source": [
    "msg = 'Who knows the answer?'\n",
    "secret = rot(msg, 17)\n",
    "\n",
    "print(secret)\n",
    "print(decode_rot(secret))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's make it a tiny bit harder.  When the secret message contains separate words, it is too easy to decode by guessing that the one-letter words are most likely \"I\" or \"a\".  So what if the encode routine mushed all the letters together:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 103,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def encode(msg, key): \n",
    "    \"Encode a message with a substitution cipher; remove non-letters.\" \n",
    "    msg = cat(tokens(msg))  ## Change here\n",
    "    table = string.maketrans(upperlower(alphabet), upperlower(key))\n",
    "    return msg.translate(table) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can decode by segmenting.  We change candidates to be a list of segmentations, and still choose the candidate with the best Pwords: "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 104,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def decode_rot(secret):\n",
    "    \"\"\"Decode a secret message that has been encoded with a rotation cipher,\n",
    "    and which has had all the non-letters squeezed out.\"\"\"\n",
    "    candidates = [segment(rot(secret, i)) for i in range(len(alphabet))]\n",
    "    return max(candidates, key=lambda msg: Pwords(msg))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 105,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "pahdghplmaxtglpxkmablmbfxtgrhgxunxeexk\n",
      "['who', 'knows', 'the', 'answer', 'this', 'time', 'anyone', 'bu', 'e', 'll', 'er']\n"
     ]
    }
   ],
   "source": [
    "msg = 'Who knows the answer this time? Anyone? Bueller?'\n",
    "secret = rot(msg, 19)\n",
    "\n",
    "print(secret)\n",
    "print(decode_rot(secret))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 109,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-123 p ah d g h p l max t g l p x km a bl mb f x t gr h g x un x e ex k\n",
      "-133 q b i eh i q m n by u hm q y l n b cm n c g y u h s i h y vo y ff y l\n",
      "-128 r c j f i jr no c z v in r z mo c d nod h z v it j i z w p z g g z m\n",
      "-115 sd k g j k so p da w j os an p de op e i a w j u k j ax q ah h an\n",
      "-144 t el h k l t p q e b x k p t b o q e f p q f j b x k v l k by r b ii b o\n",
      "-145 u f m il m u q r f cy l qu c p r f g q r g k cy l wm l c z s c j j c p\n",
      "-141 v g n j m n v r sg d z mr v d q sg h r s h l d z m x nm dat d k k d q\n",
      "-39 who knows the answer this time anyone bu e ll er\n",
      "-119 xi p l op x tu if b o t x f s u i j tu j n f b oz p of c v f mm f s\n",
      "-151 y j q m p q y u v j g c p u y g t v j ku v k o g c pa q pg d w g n n g t\n",
      "-151 z k r n q r z v w k h d q v z h u w k l v w l p h d q br q he x ho oh u\n",
      "-97 also r saw x lie r w a iv x l m w x m q i er c s r if y i pp iv\n",
      "-146 b mt p st b x y m j f s x b j w y m n x y n r j f sd t s j g z j q q j w\n",
      "-137 c n u q tu cy z n k g ty c k x z no y z os k g t eut k ha k r r k x\n",
      "-124 do v r u v d z a o l h u z d ly a op z apt l h u f v u li bl s sly\n",
      "-121 e p w s v we ab pm iv a em z b p q ab qu m iv g w v m j cm t tm z\n",
      "-142 f q x t w x f bc q n j w b fn a c q r bc r v n j wh x w n k d n u un a\n",
      "-119 gr y u x y g c dr ok x c go b dr s c d s w ok xi y x o leo v vo b\n",
      "-119 h s z vy z h des ply d h p c est de t x ply j z y pm f p w w p c\n",
      "-137 it a w z a i e ft q m ze i q d f tu e f u y q m z ka z q n g q xx q d\n",
      "-130 j u b x ab j f g u r na f jr eg u v f g v z r n alba r oh r y y re\n",
      "-125 k v cy bc k g h v sob g k s f h v w g h was o b m c b s p is z z s f\n",
      "-130 l w d z c d l hi w t p ch l t g i w x h ix b t p c nd c t q j t a at g\n",
      "-123 m x e a dem i j x u q dim u h j x y i j y c u q doe du r ku b bu h\n",
      "-124 ny f be fn j k y v re j n vi k y z j k z d v rep fe vs l v c c vi\n",
      "-134 oz g cf go k l z w s f k o w j l z ak la e w s f q g f w tm w d d w j\n"
     ]
    }
   ],
   "source": [
    "candidates = [segment(rot(secret, i)) for i in range(len(alphabet))]\n",
    "\n",
    "for c in candidates:\n",
    "    print int(log10(Pwords(c))), ' '.join(c)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What about a general substitution cipher?  The problem is that there are 26! substitution ciphers, and we can't enumerate all of them.  We would need to search through this space.  Initially make some guess at a substitution, then swap two letters; if that looks better keep going, if not try something else.  This approach solves most substitution cipher problems, although it can take a few minutes on a message of length 100 words or so.\n",
    "\n",
    "(∞ and beyond) Where To Go Next\n",
    "===\n",
    "\n",
    "What to do next?  Here are some options:\n",
    "    \n",
    "- **Spelling correction**: Use bigram or trigram context; make a model of spelling errors/edit distance; go beyond edit distance 2; make it more efficient\n",
    "- **Evaluation**: Make a serious test suite; search for best parameters (e.g. $c_1, c_2, c_3$)\n",
    "- **Smoothing**: Implement Kneser-Ney and/or Interpolation; do letter *n*-gram-based smoothing\n",
    "- **Secret Codes**: Implement a search over substitution ciphers\n",
    "- **Classification**: Given a corpus of texts, each with a classification label, write a classifier that will take a new text and return a label.  Examples: spam/no-spam; favorable/unfavorable; what author am I most like; reading level.\n",
    "- **Clustering**: Group data by similarity.  Find synonyms/related words.\n",
    "- **Parsing**: Representing nested structures rather than linear sequences of words.  relations between parts of the structure.  Implicit missing bits.  Inducing a grammar.\n",
    "- **Meaning**: What semantic relations are meant by the syntactic relations?\n",
    "- **Translation**: Using examples to transform one language into another.\n",
    "- **Question Answering**: Using examples to transfer a question into an answer, either by retrieving a passage, or by synthesizing one.\n",
    "- **Speech**: Dealing with analog audio signals rather than discrete sequences of characters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 110,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'congratulations'"
      ]
     },
     "execution_count": 110,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "correct('cpgratulations')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 94,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
